package cn.yunhe.test;


import cn.yunhe.entity.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

public class Demo1 implements Serializable {
    SessionFactory factory=null;
    Session session = null;
    Transaction tr = null;
    @Before
    public void init(){
        Configuration config = new AnnotationConfiguration().configure();
        factory = config.buildSessionFactory();
        session = factory.openSession();
        tr = session.beginTransaction();
    }
    @Test
    public void testQueryPerson(){//单独查询一张表数据
          List<Person> list = session.createQuery("from 员工").list();
          for(Person p:list){
              System.out.println(p.getUsername());
          }
    }
    @Test
    public void testOneToMany(){
        Qx qx = (Qx) session.get(Qx.class,1);
        System.out.println("区县："+qx.getQxname()+",下面的街道有：");
        Iterator<Jd> iterator = qx.getJdSet().iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next().getJdname());
        }
    }
    @Test
    public void testManyToOne(){
        Jd jd = (Jd) session.get(Jd.class,1);
        System.out.println("街道的名字为："+jd.getJdname()+",上边的区县为："+jd.getQx().getQxname());
    }
    @Test
    public void testManyToMany(){
        Student stu1 = (Student) session.get(Student.class,1);
        System.out.println("学生为："+stu1.getStudentname());
        Iterator<Course> it1 = stu1.getCourses().iterator();
        while (it1.hasNext()){
            System.out.println("课程名为："+it1.next().getCoursename());
        }
        System.out.println("=======================");
        Course cour1 = (Course) session.get(Course.class,1);
        System.out.println("课程为："+cour1.getCoursename());
        Iterator<Student> stu2 = cour1.getStudents().iterator();
        while (stu2.hasNext()){
            System.out.println("学生为："+stu2.next().getStudentname());
        }
    }
    @After
    public void destory(){
        tr.commit();
        session.close();
    }
}
